package com.jkdl.springboot.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkdl.springboot.common.util.DateTools;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.common.util.StringTools;
import com.jkdl.springboot.dao.OdrOrderMapper;
import com.jkdl.springboot.dao.OdrOrderdetailMapper;
import com.jkdl.springboot.dao.PdProductsMapper;
import com.jkdl.springboot.dao.UCompanyMapper;
import com.jkdl.springboot.domain.*;
import com.jkdl.springboot.entity.*;
import com.jkdl.springboot.service.OdrOrderdetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class OdrOrderdetailServiceImpl implements OdrOrderdetailService {

    @Autowired
    private OdrOrderdetailMapper odrOrderdetailMapper;
    @Autowired
    private UCompanyMapper uCompanyMapper;
    @Autowired
    private OdrOrderMapper odrOrderMapper;
    @Autowired
    private PdProductsMapper pdProductsMapper;

    @Override
    public List<OdrOrderdetail> list(OdrOrderdetailQueryVo odrOrderdetailQueryVo) {
        return odrOrderdetailMapper.list(odrOrderdetailQueryVo);
    }

    @Override
    public List<OdrOrderdetailWithBLOBs> listWithBLOBs(OdrOrderdetailExportQueryVo odrOrderdetailExportQueryVo) {
        return odrOrderdetailMapper.listWithBLOBs(odrOrderdetailExportQueryVo);
    }

    /**
     * 订单详细列表
     *
     * @param odrOrderdetailQueryVo
     * @return
     */
    @Override
    public PageInfo<OdrOrderdetail> selectOdrOrderdetailList(OdrOrderdetailQueryVo odrOrderdetailQueryVo) {
        PageHelper.startPage(odrOrderdetailQueryVo.getPageNum(), odrOrderdetailQueryVo.getPageSize());
        List<OdrOrderdetail> odrOrderdetailList = odrOrderdetailMapper.list(odrOrderdetailQueryVo);
        PageInfo<OdrOrderdetail> odrOrderdetailListInfo = new PageInfo<>(odrOrderdetailList);
        return odrOrderdetailListInfo;
    }

    //生成excel文件
    protected void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();

    }

    //浏览器下载excel
    protected void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            throw e;
        } finally {
            outputStream.close();
        }

    }

    /**
     * 订单导出Excel
     *
     * @param agentnamess
     * @param companyname
     * @param cuname
     * @param openids
     * @param orderid
     * @param payamount
     * @param productid
     * @param startDate
     * @param endDate
     * @param status
     * @param response
     * @return
     * @throws ParseException
     */
    public HSSFWorkbook exportOrderDetails(@RequestParam(name = "agentnamess") String agentnamess, @RequestParam(name = "companyname") String companyname, @RequestParam(name = "cuname") String cuname, @RequestParam(name = "openids") String openids, @RequestParam(name = "orderid") String orderid, @RequestParam(name = "payamount") String payamount, @RequestParam(name = "productid") Integer productid, @RequestParam(name = "startDate") String startDate, @RequestParam(name = "endDate") String endDate, @RequestParam(name = "status") String status, HttpServletResponse response) throws ParseException {
        OdrOrderdetailExportQueryVo order = new OdrOrderdetailExportQueryVo();
        OdrOrderdetailReportdatailVo odrOrderdetailReportdatailVo=new OdrOrderdetailReportdatailVo();
        odrOrderdetailReportdatailVo.setId(Integer.parseInt(agentnamess));
//       String  companyName = uCompanyMapper.getCompanyNameById(odrOrderdetailReportdatailVo);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = new Date();
        String starTimes = formatter.format(startTime);
        // System.out.print(starTimes+"------现在时间--");
        if (null != startDate && "" != startDate && null != startDate) {
            startTime = format.parse(startDate);
        } else {
            // startTime = format.parse("2017-12-12");
            startTime = format.parse(starTimes);
        }

        Date endTime = new Date();

        if (null != endDate && "" != endDate && null != endDate) {
            endTime = format.parse(endDate);
        }

        if ("".equals(status)) {
            status = null;
        }
//        order.setAgentnamess(companyName);
        order.setPayamount(payamount);
        order.setCompanyname(companyname);
       // order.setAgentnamess(agentnamess);
        //order.setCuname(cuname);
        //order.setOpenids(openids);
        order.setOrderid(orderid);
        order.setStatus(status);
        order.setStartDate(startTime);
        order.setEndDate(endTime);
        order.setProductid(productid);
        List<OdrOrderdetailWithBLOBs> odrexport = odrOrderdetailMapper.listWithBLOBs(order);
        // List<OdrOrderdetail> odrexport=orderdetailService.list(odrOrderdetailQueryVo);
        HttpHeaders headers = null;
        ByteArrayOutputStream baos = null;
        //1.创建Excel文档
        HSSFWorkbook workbook = null;
        try {
            workbook = new HSSFWorkbook();
            //2.创建文档摘要
            workbook.createInformationProperties();
            //3.获取文档信息，并配置
            DocumentSummaryInformation dsi = workbook.getDocumentSummaryInformation();
            //3.1文档类别
            dsi.setCategory("订单详情");
            //3.2设置文档管理员
            dsi.setManager("");
            //3.3设置组织机构
            dsi.setCompany("");
            //4.获取摘要信息并配置
            SummaryInformation si = workbook.getSummaryInformation();
            //4.1设置文档主题
            si.setSubject("订单详情");
            //4.2.设置文档标题
            si.setTitle("订单详情");
            //4.3 设置文档作者
            si.setAuthor("");
            //4.4设置文档备注
            si.setComments("备注信息暂无");
            //创建Excel表单
            HSSFSheet sheet = workbook.createSheet("订单信息表");
            //创建日期显示格式
            HSSFCellStyle dateCellStyle = workbook.createCellStyle();
            dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
            //创建标题的显示样式
            HSSFCellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            //定义列的宽度
            sheet.setColumnWidth(0, 14 * 256);
            sheet.setColumnWidth(1, 10 * 256);
            sheet.setColumnWidth(2, 10 * 256);
            sheet.setColumnWidth(3, 10 * 256);
            sheet.setColumnWidth(4, 20 * 256);
            sheet.setColumnWidth(5, 10 * 256);
            sheet.setColumnWidth(6, 10 * 256);
            sheet.setColumnWidth(7, 10 * 256);
            sheet.setColumnWidth(8, 16 * 256);
            sheet.setColumnWidth(9, 16 * 256);
            sheet.setColumnWidth(10, 25 * 256);
            sheet.setColumnWidth(11, 20 * 256);
            sheet.setColumnWidth(12, 18 * 256);
            sheet.setColumnWidth(13, 20 * 256);

            //5.设置表头
            HSSFRow headerRow = sheet.createRow(0);
            HSSFCell cell0 = headerRow.createCell(0);
            cell0.setCellValue("设备编号");
            cell0.setCellStyle(headerStyle);
            HSSFCell cell1 = headerRow.createCell(1);
            cell1.setCellValue("省份");
            cell1.setCellStyle(headerStyle);
            HSSFCell cell2 = headerRow.createCell(2);
            cell2.setCellValue("市/区");
            cell2.setCellStyle(headerStyle);
            HSSFCell cell3 = headerRow.createCell(3);
            cell3.setCellValue("区/县");
            cell3.setCellStyle(headerStyle);
            HSSFCell cell4 = headerRow.createCell(4);
            cell4.setCellValue("商户名称");
            cell4.setCellStyle(headerStyle);
            HSSFCell cell5 = headerRow.createCell(5);
            cell5.setCellValue("设备数量");
            cell5.setCellStyle(headerStyle);
            HSSFCell cell6 = headerRow.createCell(6);
            cell6.setCellValue("房间号");
            cell6.setCellStyle(headerStyle);
            HSSFCell cell7 = headerRow.createCell(7);
            cell7.setCellValue("订单金额");
            cell7.setCellStyle(headerStyle);
            HSSFCell cell8 = headerRow.createCell(8);
            cell8.setCellValue("订单状态");
            cell8.setCellStyle(headerStyle);

            HSSFCell cell10 = headerRow.createCell(9);
            cell10.setCellValue("openid");
            cell10.setCellStyle(headerStyle);
            HSSFCell cell11 = headerRow.createCell(10);
            cell11.setCellValue("订单日期");
            cell11.setCellStyle(headerStyle);
            HSSFCell cell12 = headerRow.createCell(11);
            cell12.setCellValue("代理商");
            cell12.setCellStyle(headerStyle);
            HSSFCell cell13 = headerRow.createCell(12);
            cell13.setCellValue("订单号");
            cell13.setCellStyle(headerStyle);
            HSSFCell cell9 = headerRow.createCell(13);
            cell9.setCellValue("客户昵称");
            cell9.setCellStyle(headerStyle);

            //6.装数据
            for (int i = 0; i < odrexport.size(); i++) {
                HSSFRow row = sheet.createRow(i + 1);
                OdrOrderdetailWithBLOBs odr = odrexport.get(i);

                row.createCell(0).setCellValue(odr.getProductid());
                row.createCell(1).setCellValue(odr.getProvincename());
                row.createCell(2).setCellValue(odr.getCityname());
                row.createCell(3).setCellValue(odr.getDistrictname());
                row.createCell(4).setCellValue(odr.getCompanyname());
                if (null != odr.getDevicenumber() && !"".equals(odr.getDevicenumber())) {
                    row.createCell(5).setCellValue(odr.getDevicenumber());
                } else {
                    row.createCell(5).setCellValue("--");
                }
                if (null != odr.getDetail() && !"".equals(odr.getDetail())) {
                    row.createCell(6).setCellValue(odr.getDetail());
                } else {
                    row.createCell(6).setCellValue("--");
                }
                row.createCell(7).setCellValue(odr.getPayamount());
                if ("10".equals(odr.getStatus())) {
                    row.createCell(8).setCellValue("支付成功");
                } else if ("0".equals(odr.getStatus())) {
                    row.createCell(8).setCellValue("待支付");
                }

                // row.createCell(8).setCellValue(odr.getStatus());
                row.createCell(9).setCellValue(odr.getOpenids());
                /*row.createCell(10).setCellValue(odr.getCreatedate());*/
                HSSFCell endContractCell = row.createCell(10);
                endContractCell.setCellValue(odr.getCreatedate());
                endContractCell.setCellStyle(dateCellStyle);
                if (null != odr.getAgentnamess() && !"".equals(odr.getAgentnamess())) {
                    row.createCell(11).setCellValue(odr.getAgentnamess());
                } else {
                    row.createCell(11).setCellValue("--");
                }
                row.createCell(12).setCellValue(odr.getOrderid());
                if (null != odr.getCuname() && !"".equals(odr.getCuname())) {
                    row.createCell(13).setCellValue(odr.getCuname());
                } else {
                    row.createCell(13).setCellValue("--");
                }

            }


            String fileName = "导出订单excel.xls";

            //生成excel文件
            buildExcelFile(fileName, workbook);

            //浏览器下载excel
            buildExcelDocument(fileName, workbook, response);

            return null;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<OdrOrderdetailWithBLOBs> listByOpenid(OdrOrderdetailQueryOpenidVo odrOrderdetailQueryOpenidVo) {
        return odrOrderdetailMapper.listByOpenid(odrOrderdetailQueryOpenidVo);
    }

    @Override
    public PageInfo<OdrOrderdetailWithBLOBs> selectOdrOrderdetailByOpenidpage(OdrOrderdetailQueryOpenidVo odrOrderdetailQueryOpenidVo) {
        PageHelper.startPage(odrOrderdetailQueryOpenidVo.getPageNum(), odrOrderdetailQueryOpenidVo.getPageSize());
        List<OdrOrderdetailWithBLOBs> odrOrderdetailWithBLOBs = odrOrderdetailMapper.listByOpenid(odrOrderdetailQueryOpenidVo);
        PageInfo<OdrOrderdetailWithBLOBs> odrOrderdetailWithBLOBsPageInfo = new PageInfo<>(odrOrderdetailWithBLOBs);
        return odrOrderdetailWithBLOBsPageInfo;
    }

    @Override
    public int selectOdrOrderdetailCountByConpanyid(OdrOrderdetailQueryCompanyidVo odrOrderdetailQueryCompanyidVo) {

        String qyid = odrOrderdetailQueryCompanyidVo.getCompanyid();
        String qyids = qyid + "";
        //String qyid1=String.valueOf(qyid);
        List<UCompanyWithBLOBs> uCompanyList = uCompanyMapper.listByParentid(odrOrderdetailQueryCompanyidVo);

        OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo = new OdrOrderdetailQueryCompanyidListVo();

        String qids = new String();// 封装二级id,查询三级

        for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyList) {

            qyids += "," + uCompanyWithBLOBs.getId();
            qids += "," + uCompanyWithBLOBs.getId();
        }
        //三级查询
        if (null != qids && qids != "" && !qids.equals("")) {
            qids = qids.substring(1, qids.length());
            //Integer qid=Integer.valueOf(qids).intValue();
            odrOrderdetailQueryCompanyidVo.setCompanyid(qids);
            List<String> companyList = Arrays.asList(qids.split(","));

            odrOrderdetailQueryCompanyidListVo.setCompanyid(companyList);

            List<UCompanyWithBLOBs> uCompanyWithBLOBsList = uCompanyMapper.listByParentidIn(odrOrderdetailQueryCompanyidListVo);
            for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyWithBLOBsList) {
                qyids += "," + uCompanyWithBLOBs.getId();
            }
        }
        qyids = qyids.substring(0, qyids.length());
        OdrOrderdetailQueryQyidsVo odrOrderdetailQueryQyidsVo = new OdrOrderdetailQueryQyidsVo();

        Date createdate = new Date();
       /* odrOrderdetailQueryQyidsVo.setStartDate(createdate);
        odrOrderdetailQueryQyidsVo.setEndDate(createdate);*/
        /* else if(!"".equals(qids)&&"".equals(qyids)){
            List<String> qyidList = Arrays.asList(qids.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);
        }*/

        if (!"".equals(qyid) && "".equals(qids)) {
            List<String> qyidList = Arrays.asList(qyid.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);
        } else {
            List<String> qyidList = Arrays.asList(qyids.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);

        }

        List<OdrOrder> odrOrderList = odrOrderMapper.listByCompanyid(odrOrderdetailQueryQyidsVo);
        int orderSize = odrOrderList.size();

        return orderSize;
    }


    @Override
    public int selectOdrOrderdetailCountnationPostageByConpanyid(OdrOrderdetailQueryCompanyidVo odrOrderdetailQueryCompanyidVo) {

        String qyid = odrOrderdetailQueryCompanyidVo.getCompanyid();
        String qyids = qyid + "";
        //String qyid1=String.valueOf(qyid);
        List<UCompanyWithBLOBs> uCompanyList = uCompanyMapper.listByParentid(odrOrderdetailQueryCompanyidVo);

        OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo = new OdrOrderdetailQueryCompanyidListVo();

        String qids = new String();// 封装二级id,查询三级

        for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyList) {

            qyids += "," + uCompanyWithBLOBs.getId();
            qids += "," + uCompanyWithBLOBs.getId();
        }
        //三级查询
        if (null != qids && qids != "" && !qids.equals("")) {
            qids = qids.substring(1, qids.length());
            //Integer qid=Integer.valueOf(qids).intValue();
            odrOrderdetailQueryCompanyidVo.setCompanyid(qids);
            List<String> companyList = Arrays.asList(qids.split(","));

            odrOrderdetailQueryCompanyidListVo.setCompanyid(companyList);

            List<UCompanyWithBLOBs> uCompanyWithBLOBsList = uCompanyMapper.listByParentidIn(odrOrderdetailQueryCompanyidListVo);
            for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyWithBLOBsList) {
                qyids += "," + uCompanyWithBLOBs.getId();
            }
        }
        qyids = qyids.substring(0, qyids.length());
        OdrOrderdetailQueryQyidsVo odrOrderdetailQueryQyidsVo = new OdrOrderdetailQueryQyidsVo();


        if (!"".equals(qyid) && "".equals(qids)) {
            List<String> qyidList = Arrays.asList(qyid.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);
        } else {
            List<String> qyidList = Arrays.asList(qyids.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);

        }
        BigDecimal a1 = BigDecimal.valueOf(1.0);
        BigDecimal a2 = BigDecimal.valueOf(2.0);
        BigDecimal a3 = BigDecimal.valueOf(3.0);
        BigDecimal a5 = BigDecimal.valueOf(5.0);

        List<OdrOrder> odrOrderList = odrOrderMapper.listByCompanyid(odrOrderdetailQueryQyidsVo);
        int size1 = 0;
        int size2 = 0;
        int size3 = 0;
        int size5 = 0;
        for (OdrOrder odrOrder : odrOrderList) {


            if (odrOrder.getAmount().compareTo(a1) == 0) {
                size1 += 1;
            } else if (odrOrder.getAmount().compareTo(a2) == 0) {
                size2 += 1;
            } else if (odrOrder.getAmount().compareTo(a3) == 0) {
                size3 += 1;
            } else if (odrOrder.getAmount().compareTo(a5) == 0) {
                size5 += 1;
            }
        }
        int orderSize = size1 + 2 * size2 + 3 * size3 + 5 * size5;

        return orderSize;
    }

    /**
     * 商家设备数量bycompanyid
     *
     * @param odrOrderdetailQueryCompanyidVo
     * @return
     */
    @Override
    public int selectOrderdetailCountPdProductByCompanyid(OdrOrderdetailQueryCompanyidVo odrOrderdetailQueryCompanyidVo) {

        String qyid = odrOrderdetailQueryCompanyidVo.getCompanyid();

        int updateCompanyid = Integer.valueOf(qyid);
        String qyids = qyid + "";
        //String qyid1=String.valueOf(qyid);
        List<UCompanyWithBLOBs> uCompanyList = uCompanyMapper.listByParentid(odrOrderdetailQueryCompanyidVo);

        OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo = new OdrOrderdetailQueryCompanyidListVo();

        String qids = new String();// 封装二级id,查询三级

        for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyList) {

            qyids += "," + uCompanyWithBLOBs.getId();
            qids += "," + uCompanyWithBLOBs.getId();
        }
        //三级查询
        if (null != qids && qids != "" && !qids.equals("")) {
            qids = qids.substring(1, qids.length());
            //Integer qid=Integer.valueOf(qids).intValue();
            odrOrderdetailQueryCompanyidVo.setCompanyid(qids);
            List<String> companyList = Arrays.asList(qids.split(","));

            odrOrderdetailQueryCompanyidListVo.setCompanyid(companyList);

            List<UCompanyWithBLOBs> uCompanyWithBLOBsList = uCompanyMapper.listByParentidIn(odrOrderdetailQueryCompanyidListVo);
            for (UCompanyWithBLOBs uCompanyWithBLOBs : uCompanyWithBLOBsList) {
                qyids += "," + uCompanyWithBLOBs.getId();
            }
        }
        qyids = qyids.substring(0, qyids.length());
        OdrOrderdetailQueryQyidsVo odrOrderdetailQueryQyidsVo = new OdrOrderdetailQueryQyidsVo();


        if (!"".equals(qyid) && "".equals(qids)) {
            List<String> qyidList = Arrays.asList(qyid.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);
        } else {
            List<String> qyidList = Arrays.asList(qyids.split(","));
            odrOrderdetailQueryQyidsVo.setQyids(qyidList);

        }

        List<PdProducts> odrOrderList = pdProductsMapper.listByCompanyid(odrOrderdetailQueryQyidsVo);
        int orderSize = odrOrderList.size();

        UCompanyUpdateDevicenumberVo uCompanyUpdateDevicenumberVo = new UCompanyUpdateDevicenumberVo();

        uCompanyUpdateDevicenumberVo.setId(updateCompanyid);
        uCompanyUpdateDevicenumberVo.setDevicenumber(orderSize);
        UCompanyWithBLOBs uCompany = uCompanyMapper.selectByPrimaryKey(updateCompanyid);
        BeanUtils.copyProperties(uCompanyUpdateDevicenumberVo, uCompany);
        uCompanyMapper.updateByPrimaryKeySelective(uCompany);

        return orderSize;
    }

    /**
     * 小程序订单是否存在并已结束
     *
     * @param xcxIsOrderAndOrderEndVo
     * @return
     */
    @Override
    public JsonResult isOrderAndEnd(XcxIsOrderAndOrderEndVo xcxIsOrderAndOrderEndVo) {

        OdrOrderdetail odrOrderdetail = odrOrderdetailMapper.isOrderAndEnd(xcxIsOrderAndOrderEndVo);
        if (odrOrderdetail == null) {
            return JsonResult.build("订单不存在");
        }

        long endDateMillis = DateTools.getMillis(odrOrderdetail.getCdendtime());
        long nowDateMillis = DateTools.getMillis(new Date());
        if (nowDateMillis > endDateMillis) {
            return JsonResult.build("订单已过期");
        }

        //设备信息
        PdProducts pdProducts = pdProductsMapper.selectByPrimaryKey(xcxIsOrderAndOrderEndVo.getProductId());

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", odrOrderdetail.getOrderid());
        map.put("batchNumber", pdProducts.getBatchnumber());

        return JsonResult.ok(map);
    }

    @Override
    public JsonResult listAllLotUser(OdrOrderMonthListVo odrOrderMonthListVo) throws Exception {

        //本月第一天零点
        Date startDate = DateTools.getMonFirstDay();
        //当前日期
        Date endDate = new Date();

        //当前月
        int month = DateTools.getMonth(endDate);
        int year = DateTools.getYear(endDate);

        List<Date> listDate = DateTools.findDates(startDate, endDate);

        int orderCount[] = new int[listDate.size()];

        int orderDate[] = new int[listDate.size()];

        Map<String, Object> map = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        for (int i = 0; i < listDate.size() - 1; i++) {

            OdrOrderDayCountVo odrOrderDayCountVo = new OdrOrderDayCountVo();
            odrOrderDayCountVo.setCompanyId(odrOrderMonthListVo.getCompanyId());
            odrOrderDayCountVo.setStatus(100);
            odrOrderDayCountVo.setStartDate(sdf.parse(DateFormatUtils.format(listDate.get(i), "yyyy-MM-dd 00:00:00")));
            odrOrderDayCountVo.setEndDate(sdf.parse(DateFormatUtils.format(listDate.get(i + 1), "yyyy-MM-dd 00:00:00")));
            int odrCount = odrOrderMapper.orderCount(odrOrderDayCountVo);
            orderCount[i] = odrCount;
            orderDate[i] = i + 1;
        }

        OdrOrderDayCountVo odrOrderDayCountVo = new OdrOrderDayCountVo();
        odrOrderDayCountVo.setCompanyId(odrOrderMonthListVo.getCompanyId());
        odrOrderDayCountVo.setStatus(10);
        odrOrderDayCountVo.setStartDate(sdf.parse(DateFormatUtils.format(listDate.get(0), "yyyy-MM-dd 00:00:00")));
        odrOrderDayCountVo.setEndDate(sdf.parse(DateFormatUtils.format(listDate.get(listDate.size() - 1), "yyyy-MM-dd 00:00:00")));
        int allOrderSuccessCount = odrOrderMapper.orderCount(odrOrderDayCountVo);

        OdrOrderDayCountVo odrOrderDayCountVo2 = new OdrOrderDayCountVo();
        odrOrderDayCountVo2.setCompanyId(odrOrderMonthListVo.getCompanyId());
        odrOrderDayCountVo2.setStatus(100);
        odrOrderDayCountVo2.setStartDate(sdf.parse(DateFormatUtils.format(listDate.get(0), "yyyy-MM-dd 00:00:00")));
        odrOrderDayCountVo2.setEndDate(sdf.parse(DateFormatUtils.format(listDate.get(listDate.size() - 1), "yyyy-MM-dd 00:00:00")));
        int allOrderCount = odrOrderMapper.orderCount(odrOrderDayCountVo2);

        map.put("orderCount", orderCount);

        map.put("orderDate", orderDate);

        int[] arr = Arrays.copyOf(orderCount, orderCount.length);
        Arrays.sort(arr);//升序排列
        int maxCount = arr[arr.length - 1];

        map.put("allOrderSuccessCount", allOrderSuccessCount);
        map.put("allOrderCount", allOrderCount);
        map.put("maxCount", maxCount);
        map.put("month", month);
        map.put("year", year);

        return JsonResult.ok(map);
    }

    /**
     *   根据条件查询设备使用数量
     */
    @Override
    public List<String> getproductNumber(OdrOrderdetailReportdatailVo odrOrderdetailReportdatailVo){
        return odrOrderdetailMapper.getproductNumber(odrOrderdetailReportdatailVo);
    }

    @Override
    public JsonResult orderReportdatail(OdrOrderdetailReportdatailVo odrOrderdetailReportdatailVo){
        PdProductCountQueryVo pdProductCountQueryVo=new PdProductCountQueryVo();
        OrderReportdatailExample orderReportdatailExample=new OrderReportdatailExample();
        UCompanyQueryPlatformVo  uCompanyQueryPlatformVo=new UCompanyQueryPlatformVo();
        List<UCompany> uCompanyList = new ArrayList<>();
        Integer oneCompanyId  =odrOrderdetailReportdatailVo.getGrandParentId() ;
        Integer   companypdProductCount =0;
        Integer tooCompanyId  =odrOrderdetailReportdatailVo.getParentid() ;
        OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo=new OdrOrderdetailQueryCompanyidListVo();
        List<PdProductsWithBLOBs>  pdProductslist;
        List<String> ids = new ArrayList<String>();
        List<String>  luohuTingCount=new ArrayList<String>(); //罗湖区大厅使用过的设备

        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        int companyIdByNameCount = 0;
        int luohudating = 0;
        if(oneCompanyId != null && !oneCompanyId.equals("")) {


            if("1875".equals(oneCompanyId) || 1875==oneCompanyId){
                luohuTingCount= odrOrderdetailMapper.getproductLuohuTingCount(odrOrderdetailReportdatailVo);
                HashSet h = new HashSet(luohuTingCount);
                luohuTingCount.clear();
                luohuTingCount.addAll(h);
                //罗湖区大厅使用设备
                luohudating = luohuTingCount.size();
            }

            if(tooCompanyId != null && !tooCompanyId.equals("")){//判断一级和二级

                odrOrderdetailQueryCompanyidListVo.setId(tooCompanyId);
                if(odrOrderdetailReportdatailVo.getCompanyname() != null && odrOrderdetailReportdatailVo.getCompanyname() != "") {
                    uCompanyQueryPlatformVo.setParentId(tooCompanyId);
                    uCompanyQueryPlatformVo.setCompanyType("50");
                    List<UCompany> uCompanyList2 = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                    for (UCompany uCompany1 : uCompanyList2) {
                        ids.add(uCompany1.getId().toString());
                    }
                    pdProductCountQueryVo.setCompanyid(ids);
                    pdProductCountQueryVo.setCompanyname(odrOrderdetailReportdatailVo.getCompanyname());
                    //通过商户名称获取设备数量
                    companyIdByNameCount = uCompanyMapper.getProductCountByName(pdProductCountQueryVo);
                }
            }else{
                odrOrderdetailQueryCompanyidListVo.setId(oneCompanyId);
                uCompanyQueryPlatformVo.setParentId(oneCompanyId);
                uCompanyQueryPlatformVo.setCompanyType("20");

                uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                //二级代理商自身ID
                List<String> idstoo =new ArrayList<String>(uCompanyList.size());
                for(UCompany uCompany2 : uCompanyList){
                    idstoo.add(uCompany2.getId().toString());
                }
                idstoo.add(oneCompanyId.toString());
                odrOrderdetailQueryCompanyidListVo.setCompanyid(idstoo);

                for (int i=0;i<uCompanyList.size();i++){
                    ids.add(uCompanyList.get(i).getId().toString());
                }
                if(odrOrderdetailReportdatailVo.getCompanyname() != null && odrOrderdetailReportdatailVo.getCompanyname() != "") {
                    ids.clear();
//                    if(tooCompanyId != null && !tooCompanyId.equals("")) {
                        for (UCompany uCompany : uCompanyList) {
                            int id = uCompany.getId();

                            uCompanyQueryPlatformVo.setParentId(id);
                            uCompanyQueryPlatformVo.setCompanyType("50");
                            List<UCompany> uCompanyList2 = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                            for (UCompany uCompany1 : uCompanyList2) {
                                ids.add(uCompany1.getId().toString());
                            }
                        }
//                    }
                    pdProductCountQueryVo.setCompanyid(ids);
                    pdProductCountQueryVo.setCompanyname(odrOrderdetailReportdatailVo.getCompanyname());
                    //通过商户名称获取设备数量
                    companyIdByNameCount = uCompanyMapper.getProductCountByName(pdProductCountQueryVo);


                }

                companypdProductCount=pdProductsMapper.getcompanypdProductCount(odrOrderdetailQueryCompanyidListVo);
            }
    //            companypdProductCount=pdProductsMapper.getcompanypdProductCount(odrOrderdetailQueryCompanyidListVo);


            if(tooCompanyId != null && !tooCompanyId.equals("")){//判断一级和二级
    //                odrOrderdetailQueryCompanyidListVo.setId(tooCompanyId);
                ids.clear();
                companypdProductCount = 0;
                ids.add(tooCompanyId.toString());
                odrOrderdetailQueryCompanyidListVo.setCompanyid(ids);
            }else{
                odrOrderdetailQueryCompanyidListVo.setId(oneCompanyId);
                odrOrderdetailQueryCompanyidListVo.setCompanyid(ids);
            }

        }
        Integer totalpdProduct = 0;
        if(ids.size() == 0 && companypdProductCount > 0){
    //            //设备总数量
    //            totalpdProduct =  pdProductsMapper.getequipmentNumber(odrOrderdetailQueryCompanyidListVo);
        }else{
            //设备总数量
            totalpdProduct =  pdProductsMapper.getequipmentNumber(odrOrderdetailQueryCompanyidListVo);
        }

        //设备=  pdProductsMapper.getequipmentNumber(odrOrderdetailQueryCompanyidListVo);

        //使用设备数量 (使用过的所有设备）
        List<String>  productNumberList= odrOrderdetailMapper.getproductNumber(odrOrderdetailReportdatailVo);


        HashSet h = new HashSet(productNumberList);
        productNumberList.clear();
        productNumberList.addAll(h);
        //设备使用数量
        int productNumber = productNumberList.size();

        //总金额
        OrderReportdatailExample totalmoneyInfo = odrOrderMapper.gettotalMoney(odrOrderdetailReportdatailVo);
        //查询折现图数据
        List<OdrOrderGroup>   OdrOrderGrouplist=  odrOrderMapper.getreportFormsList(odrOrderdetailReportdatailVo);
        if(null != totalmoneyInfo ){
            orderReportdatailExample.setTotalMoney(totalmoneyInfo.getTotalMoney());
            // orderReportdatailExample.setCompanyname(totalmoneyInfo.getCompanyname());
        }else{
            orderReportdatailExample.setTotalMoney(0);
        }
        //名词
        String companyName = uCompanyMapper.getCompanyName(odrOrderdetailReportdatailVo);
        if(odrOrderdetailReportdatailVo.getCompanyname()!=null && ! odrOrderdetailReportdatailVo.getCompanyname().equals("")){
            orderReportdatailExample.setCompanyname(odrOrderdetailReportdatailVo.getCompanyname());
        }else{
            orderReportdatailExample.setCompanyname(companyName);
        }

        //设备使用数量
        orderReportdatailExample.setUsageQuantity(productNumber);
        //报表数据

        OdrOrderGrouplist.stream().forEach(obj->{
            if(StringTools.isBlank(odrOrderdetailReportdatailVo.getCompanyname())){
                obj.setValue(obj.getValue()+obj.getCounttoo());
            }
        });
        orderReportdatailExample.setOdrOrderGroupList(OdrOrderGrouplist);
                Map<Object,String> maps;
         //设备总数量

        int  pdProductCount = totalpdProduct+companypdProductCount;
        if(companyIdByNameCount == 0){
            orderReportdatailExample.setEquipmentNumber(pdProductCount);
        }else{
            orderReportdatailExample.setEquipmentNumber(companyIdByNameCount);
        }



        //设备使用率
        double utilizationRate =0;
        if( 0 == productNumber && 0 == totalpdProduct.intValue() ){
            utilizationRate = 0;
        }else{
            if(null != odrOrderdetailReportdatailVo.getCompanyname() && !odrOrderdetailReportdatailVo.getCompanyname().equals("")){
                if(companyIdByNameCount>0){
                    utilizationRate = Double.parseDouble(numberFormat.format((float)productNumber /(float)companyIdByNameCount * 100).replaceAll(",",""));
                }else{
                    utilizationRate = Double.parseDouble(numberFormat.format((float)productNumber /(float)pdProductCount * 100).replaceAll(",",""));
                }
            }else{
                utilizationRate = Double.parseDouble(numberFormat.format((float)productNumber /(float)pdProductCount * 100).replaceAll(",",""));
            }

            //utilizationRate= productNumber / totalpdProduct * 100;
        }

        //BigDecimal servicechargenew = new BigDecimal(utilizationRate);
        //utilizationRate = servicechargenew.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        //使用率
        orderReportdatailExample.setUtilizationRate(utilizationRate);

        //罗湖区大厅使用率
        double luohuhall = 0;
        //罗湖区房间使用率
        double luohuroom = 0;
        if(luohudating>0){
            if(null != odrOrderdetailReportdatailVo.getCompanyname() && !odrOrderdetailReportdatailVo.getCompanyname().equals("")){
                 luohuhall = Double.parseDouble(numberFormat.format((float)luohudating /(float)companyIdByNameCount * 100));
            }else{
                luohuhall = Double.parseDouble(numberFormat.format((float)luohudating /(float)pdProductCount * 100));
            }
            luohuroom = Double.parseDouble(numberFormat.format(utilizationRate - luohuhall));
            orderReportdatailExample.setLuohuhall(luohuhall);
            orderReportdatailExample.setLuohuRoom(luohuroom);
        }else{
            orderReportdatailExample.setLuohuhall(0);
            orderReportdatailExample.setLuohuRoom(utilizationRate);
        }

        log.info("罗湖区大厅使用率----------------------"+luohuhall);
        log.info("罗湖区房间使用率----------------------"+luohuroom);

        //两元使用率
        double two = 0;
        //三元使用率
        double thrre = 0;
        odrOrderdetailReportdatailVo.setPrice(2);
        List<String>  towOrderList= odrOrderdetailMapper.getproductNumber(odrOrderdetailReportdatailVo);
        HashSet t = new HashSet(towOrderList);
        towOrderList.clear();
        towOrderList.addAll(t);
        odrOrderdetailReportdatailVo.setPrice(3);
        List<String>  thrreOrderList= odrOrderdetailMapper.getproductNumber(odrOrderdetailReportdatailVo);
        HashSet r = new HashSet(thrreOrderList);
        thrreOrderList.clear();
        thrreOrderList.addAll(r);

        if(towOrderList.size()>0 || thrreOrderList.size()>0){

            if(null != odrOrderdetailReportdatailVo.getCompanyname() && !odrOrderdetailReportdatailVo.getCompanyname().equals("")){
                if(companyIdByNameCount>0){
                    two = Double.parseDouble(numberFormat.format((float)towOrderList.size() /(float)companyIdByNameCount * 100));
                    thrre = Double.parseDouble(numberFormat.format((float)thrreOrderList.size() /(float)companyIdByNameCount * 100));
                }

            }else{
            two = Double.parseDouble(numberFormat.format((float)towOrderList.size() /(float)pdProductCount * 100));
            thrre = Double.parseDouble(numberFormat.format((float)thrreOrderList.size() /(float)pdProductCount * 100));
            }
            orderReportdatailExample.setTwo(two);
            orderReportdatailExample.setThree(thrre);
        }else{
            orderReportdatailExample.setTwo(0);
            orderReportdatailExample.setThree(0);
        }


        log.info("二元使用率----------------------"+two);
        log.info("三元使用率----------------------"+thrre);

        return JsonResult.ok(orderReportdatailExample);
    }



    /**
     *   用于查询罗湖区大厅设备使用率
     */

    @Override
    public List<String> getproductLuohuTingCount(OdrOrderdetailReportdatailVo odrOrderdetailReportdatailVo){

        return  odrOrderdetailMapper.getproductLuohuTingCount(odrOrderdetailReportdatailVo);
    };


}
